package com.bell.atensettings.settingDetails;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.http.conn.util.InetAddressUtils;

import com.bell.atensettings.R;
import com.bell.atensettings.R.id;
import com.bell.atensettings.widgets.SwitchButton;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ethernet.EthernetDevInfo;
import android.net.ethernet.EthernetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EthernetSettings extends Activity
{
    private ConnectivityManager mService;
    private EthernetManager mEthManager;
    private final IntentFilter mFilter;
    private final BroadcastReceiver mEthStateReceiver;
    private EthernetDevInfo mEthInfo;
    private List<EthernetDevInfo> mListDevices = new ArrayList<EthernetDevInfo>();

    private LinearLayout mLayout_ip;
    private LinearLayout mLayout_mask;
    private LinearLayout mLayout_gate;
    private LinearLayout mLayout_dns1;
    private LinearLayout mLayout_dns2;
    private SwitchButton iv_flag;
    private TextView tv_title;
    private TextView tv_flag;
    private TextView tv_status;
    private SwitchButton iv_auto;
    private EditText mIP_text;
    private EditText mMask_Text;
    private EditText mGate_text;
    private EditText mDns1_text;
    private EditText mDns2_text;
    private TextView mMac_text;
    private Button mConnBtn;

    private boolean ether_tag = true;
    private boolean auto_flag = false;

    public EthernetSettings() {
        mFilter = new IntentFilter();
        mFilter.addAction(EthernetManager.ETHERNET_STATE_CHANGED_ACTION);
        mFilter.addAction(EthernetManager.NETWORK_STATE_CHANGED_ACTION);

        mEthStateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                handleEvent(context, intent);
            }
        };
    }

    private void handleEvent(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (EthernetManager.ETHERNET_STATE_CHANGED_ACTION.equals(action)) {
            final EthernetDevInfo devinfo = (EthernetDevInfo) intent
                    .getParcelableExtra(EthernetManager.EXTRA_ETHERNET_INFO);
            final int event = intent.getIntExtra(EthernetManager.EXTRA_ETHERNET_STATE, EthernetManager.EVENT_NEWDEV);

            if (event == EthernetManager.EVENT_NEWDEV || event == EthernetManager.EVENT_DEVREM) {
                setDevicesList(devinfo);
            }
        } else if (EthernetManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
            final String NONE_IP = "0.0.0.0";
            final NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(EthernetManager.EXTRA_NETWORK_INFO);
            final int event = intent.getIntExtra(EthernetManager.EXTRA_ETHERNET_STATE,
                    EthernetManager.EVENT_CONFIGURATION_SUCCEEDED);

            switch (event) {
                case EthernetManager.EVENT_CONFIGURATION_SUCCEEDED:
                    mEthInfo = mEthManager.getSavedConfig();
                    if (mEthInfo != null) {
                        setDevicesList(mEthInfo);
                    }
                    tv_status.setText(mEthInfo.getIfName() + "-已连接");
                    break;
                case EthernetManager.EVENT_CONFIGURATION_FAILED:

                    mIP_text.setText(NONE_IP);
                    mMask_Text.setText(NONE_IP);
                    mGate_text.setText(NONE_IP);
                    mDns1_text.setText(NONE_IP);
                    break;
                case EthernetManager.EVENT_DISCONNECTED:
                    tv_status.setText(mEthInfo.getIfName() + "-未连接");
                    mIP_text.setText(NONE_IP);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        overridePendingTransition(R.anim.start, R.anim.push_left_out);
    }

    private String getLocalIpAddress()
    {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())
                            && !inetAddress.getHostAddress().toString().equals("null")
                            && inetAddress.getHostAddress() != null) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }

    private void initView()
    {
        tv_title = (TextView) findViewById(R.id.setting_title);
        iv_flag = (SwitchButton) findViewById(R.id.on_off);
        tv_flag = (TextView) findViewById(R.id.tv);
        tv_status = (TextView) findViewById(R.id.tv_status);
        iv_auto = (SwitchButton) findViewById(R.id.iv_auto);
        mIP_text = (EditText) findViewById(R.id.ip_address);
        mMask_Text = (EditText) findViewById(R.id.mask_address);
        mGate_text = (EditText) findViewById(R.id.gateway_address);
        mDns1_text = (EditText) findViewById(R.id.dns1_address);
        mDns2_text = (EditText) findViewById(R.id.dns2_address);
        mMac_text = (TextView) findViewById(R.id.mac_address);
        mLayout_ip = (LinearLayout) findViewById(R.id.ll_ip);
        mLayout_mask = (LinearLayout) findViewById(R.id.ll_mask);
        mLayout_gate = (LinearLayout) findViewById(R.id.ll_gateway);
        mLayout_dns1 = (LinearLayout) findViewById(R.id.ll_dns1);
        mLayout_dns2 = (LinearLayout) findViewById(R.id.ll_dns2);
        mConnBtn = (Button) findViewById(R.id.btconnect);

        tv_title.setText("有线设置");
        tv_flag.setText("有线网络");
        mLayout_dns2.setVisibility(View.GONE);

        if (mEthManager.getState() == EthernetManager.ETHERNET_STATE_ENABLED) {
            ether_tag = true;
            iv_flag.setChecked(true);
        } else {
            ether_tag = false;
            iv_flag.setChecked(false);
            iv_auto.setEnabled(false);
        }

        if (mService != null) {
            NetworkInfo networkinfo = mService.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
            if (networkinfo.isConnected())
                tv_status.setText(mEthInfo.getIfName() + "-已连接");
            else
                tv_status.setText(mEthInfo.getIfName() + "-未连接");
        }
    }

    private void initListener()
    {
        iv_flag.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean checked)
            {
                ether_tag = checked;
                if (ether_tag) {
                    setEthEnabled(ether_tag);
                } else {
                    setEthEnabled(ether_tag);
                }
            }
        });

        iv_auto.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton button, boolean checked)
            {
                auto_flag = checked;
                if (ether_tag && checked) {
                    setWidgetEnabled(auto_flag);
                } else if (ether_tag) {
                    setWidgetEnabled(auto_flag);
                }
            }
        });
    }

    private void setDevicesList(EthernetDevInfo devInfo)
    {
        String ifname = "";
        mListDevices = mEthManager.getDeviceNameList();

        if (devInfo != null)
            ifname = devInfo.getIfName();
        setWidgetEnabled(false);

        if (mListDevices != null) {
            for (EthernetDevInfo deviceinfo : mListDevices) {
                if (deviceinfo.getIfName().equals(ifname)) {
                    if (deviceinfo.getConnectMode() == EthernetDevInfo.ETHERNET_CONN_MODE_DHCP) {
                        iv_auto.setChecked(false);
                        devInfo.setIpAddress(getLocalIpAddress());
                    } else if (deviceinfo.getConnectMode() == EthernetDevInfo.ETHERNET_CONN_MODE_MANUAL) {
                        iv_auto.setChecked(true);
                        setWidgetEnabled(true);
                        devInfo.setIpAddress(deviceinfo.getIpAddress());
                    }
                    devInfo.setHwaddr(deviceinfo.getHwaddr());
                    devInfo.setConnectMode(deviceinfo.getConnectMode());
                    devInfo.setDnsAddr(deviceinfo.getDnsAddr());
                    devInfo.setIfName(deviceinfo.getIfName());
                    devInfo.setNetMask(deviceinfo.getNetMask());
                    devInfo.setGateWay(deviceinfo.getGateWay());
                } else {
                    Log.i("EthernetDevInfo", deviceinfo.getIfName() + " " + deviceinfo.getHwaddr());
                }
            }

            mIP_text.setText(devInfo.getIpAddress());
            mMask_Text.setText(devInfo.getNetMask());
            mGate_text.setText(devInfo.getGateWay());
            mDns1_text.setText(devInfo.getDnsAddr());
            mMac_text.setText(devInfo.getHwaddr());
        } else {
            final String NONE_IP = "0.0.0.0";

            mIP_text.setText(NONE_IP);
            mMask_Text.setText(NONE_IP);
            mGate_text.setText(NONE_IP);
            mDns1_text.setText(NONE_IP);

        }
    }

    private void setWidgetEnabled(final boolean enable)
    {
        if (enable) {
            mIP_text.setEnabled(true);
            mIP_text.setFocusable(true);
            mIP_text.setBackgroundResource(R.drawable.inputtext);
            mIP_text.setText("");
            mLayout_mask.setVisibility(View.VISIBLE);
            mLayout_gate.setVisibility(View.VISIBLE);
            mLayout_dns1.setVisibility(View.VISIBLE);
            mConnBtn.setVisibility(View.VISIBLE);

        } else {
            mIP_text.setEnabled(false);
            mIP_text.setFocusable(false);
            mIP_text.setText(getLocalIpAddress());
            mIP_text.setBackgroundResource(R.drawable.normal_input);
            mLayout_mask.setVisibility(View.GONE);
            mLayout_gate.setVisibility(View.GONE);
            mLayout_dns1.setVisibility(View.GONE);
            mConnBtn.setVisibility(View.GONE);

        }
    }

    private void getDevInfo()
    {
        if (auto_flag) {
            mEthInfo.setConnectMode(EthernetDevInfo.ETHERNET_CONN_MODE_MANUAL);
            mEthInfo.setIpAddress(mIP_text.getText().toString());
            mEthInfo.setNetMask(mMask_Text.getText().toString());
            mEthInfo.setGateWay(mGate_text.getText().toString());
            mEthInfo.setDnsAddr(mDns1_text.getText().toString());
            mEthInfo.setHwaddr(mMac_text.getText().toString());
        }
    }

    private void setEthEnabled(final boolean enable)
    {

        new AsyncTask<Void, Void, Void>() {

            protected void onPreExecute()
            {
                // Disable button
                iv_flag.setEnabled(false);
                iv_auto.setEnabled(false);
                mConnBtn.setEnabled(false);
            }

            @Override
            protected Void doInBackground(Void... unused)
            {
                try {
                    if ((mEthManager.isConfigured() != true) && (enable == true)) {
                        publishProgress();
                    } else {
                        mEthManager.setEnabled(enable);
                    }
                    Thread.sleep(500);
                } catch (Exception e) {
                }
                return null;
            }

            protected void onProgressUpdate(Void... unused)
            {
                mEthManager.updateDevInfo(mEthInfo);
                mEthManager.setEnabled(enable);
            }

            protected void onPostExecute(Void unused)
            {
                iv_flag.setEnabled(true);
                iv_auto.setEnabled(true);
                mConnBtn.setEnabled(true);
            }
        }.execute();
    }

    public void doClick(View view)
    {
        if (view.getId() == R.id.btconnect) {
            getDevInfo();
            new AsyncTask<Void, Void, Void>() {
                protected void onPreExecute()
                {
                    iv_flag.setEnabled(false);
                    iv_auto.setEnabled(false);
                    mConnBtn.setEnabled(false);
                }

                @Override
                protected Void doInBackground(Void... unused)
                {
                    try {
                        mEthManager.updateDevInfo(mEthInfo);
                        Thread.sleep(500);
                    } catch (Exception e) {
                    }
                    return null;
                }

                protected void onProgressUpdate(Void... unused)
                {
                }

                protected void onPostExecute(Void unused)
                {
                    iv_flag.setEnabled(true);
                    iv_auto.setEnabled(true);
                    mConnBtn.setEnabled(true);
                }
            }.execute();
        }
    }

    @Override
    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(R.layout.netinfo_settings);

        try {
            mService = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            mEthManager = EthernetManager.getInstance();
            mEthInfo = mEthManager.getSavedConfig();
            initView();
        } catch (Exception exception) {
            Log.e("Exception", exception.getMessage());
        }

        initListener();

        if (mEthInfo != null) {
            setDevicesList(mEthInfo);
        } else {
            setDevicesList(null);
        }
    }

    @Override
    protected void onPause()
    {
        unregisterReceiver(mEthStateReceiver);
        super.onPause();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        registerReceiver(mEthStateReceiver, mFilter);
    }

}
